package org.vincen.helloworld.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class CRUD {
	
	private final String readStatement = "select * from pet";
	private final String insertStatement = "insert into pet values ('eri', 'vincen', 'cat', 'm', '2000-01-01', null)";
	PreparedStatement statement = null;
	
	public void read (Connection conn) throws SQLException {
		try {
			statement = conn.prepareStatement(readStatement);
			statement.executeQuery();
			resultHandler(statement);
		} finally {
			statement.close();
		}
	}
	
	protected int insert(Connection conn) throws SQLException {
		int rowAffect = -1;
		try {
			statement = conn.prepareStatement(insertStatement);
			rowAffect = statement.executeUpdate();
		} finally {
			statement.close();
		}
		return rowAffect;
	}
	
	private void resultHandler(Statement stat) throws SQLException {
		ResultSet rs = stat.getResultSet();
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		for (int i = 1; i <= columnCount; ++i) {
			if (i > 1) {
				System.out.print("\t");
			}
			System.out.print(rsmd.getColumnLabel(i));
		}
		System.out.println();
		while (rs.next()) {
			for (int i = 1; i <= columnCount; ++i) {
				if (i > 1) {
					System.out.print("\t");
				}
				System.out.print(rs.getString(i));
			}
			System.out.println();
		}
	}
}
